package com.itstu.service.impl;

import com.itstu.mapper.ApplyMapper;
import com.itstu.mapper.FriendMapper;
import com.itstu.pojo.Apply;
import com.itstu.pojo.User;
import com.itstu.pojo.dto.ApplyDTO;
import com.itstu.service.ApplyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName ApplyServiceImpl
 * @Description TODO
 * @Date 2024/10/08 21:41
 */
@Service
public class ApplyServiceImpl implements ApplyService {

    @Resource
    private ApplyMapper applyMapper;
    @Resource
    private FriendMapper friendMapper;

    /**
     * 添加申请
     * @param apply 申请信息
     */
    @Override
    public void addApply(Apply apply) {
        int i = applyMapper.addApply(apply);
        if (i == 0) {
            throw new RuntimeException("申请失败");
        }
    }

    /**
     * 获取好友列表
     * @param uid 登录用户id
     * @return 好友列表
     */
    @Override
    public List<User> getFriendsByUid(Long uid) {
        return applyMapper.getFriendsByUid(uid);
    }

    /**
     * 根据用户id和好友id获取申请信息
     * @param apply 申请信息
     * @return 申请信息
     */
    @Override
    public Apply getFriendsByUidAndTid(Apply apply) {
        return applyMapper.getFriendsByUidAndTid(apply);
    }


    /**
     * 同意或拒绝申请
     * @param applyDTO 申请信息（status: 1 接受 -- 0 拒绝）
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void agreeOrReject(ApplyDTO applyDTO) {
        String status = applyDTO.getStatus();
        Long uid = applyDTO.getUid();
        Long tid = applyDTO.getTid();
        // 根据状态判断是同意还是拒绝
        if (status.equals("1")) {
            // 同意  删除申请信息，，新增好友关系
            // 删除相互的好友申请
            applyMapper.deleteApply(uid, tid);
            // 成为相互的好友
            friendMapper.addFriendEachOther(uid, tid);
        } else {
            // 拒绝  删除申请信息
            applyMapper.deleteApply(uid, tid);
        }
    }
}
